package com.ruoyi.question.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.ruoyi.question.domain.QueListDetails;
import com.ruoyi.question.service.IQueListDetailsService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.question.domain.QueQuestions;
import com.ruoyi.question.service.IQueQuestionsService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 题库管理Controller
 * 
 * @author ruoyi
 * @date 2025-02-14
 */
@Controller
@RequestMapping("/question/questions")
public class QueQuestionsController extends BaseController
{
    private String prefix = "question/questions";

    @Autowired
    private IQueQuestionsService queQuestionsService;

    @Autowired
    private IQueListDetailsService queListDetailsServic;

    @RequiresPermissions("question:questions:view")
    @GetMapping()
    public String questions()
    {
        return prefix + "/questions";
    }

    /**
     * 查询题库管理列表
     */
    @RequiresPermissions("question:questions:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(QueQuestions queQuestions)
    {
        startPage();
        List<QueQuestions> list = queQuestionsService.selectQueQuestionsList(queQuestions);
        return getDataTable(list);
    }

    /**
     * 查询题库管理列表
     */
    @RequiresPermissions("question:questions:list")
    @PostMapping("/detailsList/{id}")
    @ResponseBody
    public TableDataInfo detailsList(@PathVariable("id") String id)
    {
        startPage();
        QueListDetails queListDetails = new QueListDetails();
        queListDetails.setListId(id);
        List<QueQuestions> list = queListDetailsServic.selectQueListDetailsList(queListDetails);
        return getDataTable(list);
    }

    /**
     * 查询题库管理列表
     */
    @RequiresPermissions("question:questions:list")
    @PostMapping("/lists")
    @ResponseBody
    public TableDataInfo lists(QueQuestions queQuestions)
    {
        startPage();
        List<QueQuestions> list = queQuestionsService.selectQueQuestionsList(queQuestions);
        return getDataTable(list);
    }

    /**
     * 导出题库管理列表
     */
    @RequiresPermissions("question:questions:export")
    @Log(title = "题库管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(QueQuestions queQuestions)
    {
        List<QueQuestions> list = queQuestionsService.selectQueQuestionsList(queQuestions);
        ExcelUtil<QueQuestions> util = new ExcelUtil<QueQuestions>(QueQuestions.class);
        return util.exportExcel(list, "题库管理数据");
    }

    /**
     * 新增题库管理
     */
    @RequiresPermissions("question:questions:add")
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    @PostMapping("/image")
    public ResponseEntity<Map<String, Object>> uploadImage(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                result.put("success", false);
                result.put("message", "只允许上传图片文件");
                return ResponseEntity.badRequest().body(result);
            }

            // 生成唯一文件名
            String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();

            // 按日期生成文件夹
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String dateFolder = LocalDateTime.now().format(formatter);

            // 构建文件路径
            String baseDir = "D:\\path"; // 基础目录
            String uploadDir = baseDir + "\\" + dateFolder; // 完整目录路径

            // 创建目录（如果不存在）
            File targetDir = new File(uploadDir);
            if (!targetDir.exists()) {
                boolean created = targetDir.mkdirs(); // 创建目录（包括父目录）
                if (!created) {
                    result.put("success", false);
                    result.put("message", "无法创建目录：" + uploadDir);
                    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
                }
            }

            // 保存文件
            String filePath = Paths.get(uploadDir, fileName).toString();
            file.transferTo(new File(filePath));

            // 返回图片 URL
            String imageUrl = "http://127.0.0.1/uploads/" + dateFolder + "/" + fileName; // 修改为你的文件访问路径
            result.put("success", true);
            result.put("url", imageUrl);
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            result.put("success", false);
            result.put("message", "文件上传失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 新增保存题库管理
     */
    @RequiresPermissions("question:questions:add")
    @Log(title = "题库管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(QueQuestions queQuestions)
    {
        return toAjax(queQuestionsService.insertQueQuestions(queQuestions));
    }

    /**
     * 修改题库管理
     */
    @RequiresPermissions("question:questions:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        QueQuestions queQuestions = queQuestionsService.selectQueQuestionsById(id);
        mmap.put("queQuestions", queQuestions);
        return prefix + "/edit";
    }

    /**
     * 修改保存题库管理
     */
    @RequiresPermissions("question:questions:edit")
    @Log(title = "题库管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(QueQuestions queQuestions)
    {
        return toAjax(queQuestionsService.updateQueQuestions(queQuestions));
    }

    /**
     * 删除题库管理
     */
    @RequiresPermissions("question:questions:remove")
    @Log(title = "题库管理", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(queQuestionsService.deleteQueQuestionsByIds(ids));
    }
}
